package com.yeb.server.config.rabbitmq;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yeb.server.pojo.MailConstants;
import com.yeb.server.pojo.MailLog;
import com.yeb.server.service.IMailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/** rabbitmq 配置类
 * @Author liushizhong
 * @Date 2021/12/30 21:42
 * @Version 1.0
 */
@Configuration
public class RabbitMQConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQConfig.class);

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory; // 连接工厂，用于创建rabbitTemplate
    @Autowired
    private IMailLogService mailLogService;


    @Bean
    public RabbitTemplate rabbitTemplate(){ // rabbitmq 模板
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        /**
         * 通过实现 ConfirmCallback 接口，消息发送到 Broker 后触发回调，
         * 确认消息是否到达 Broker 服务器，也就是只确认是否正确到达 Exchange 中
         * data:消息
         * ack：是否确认
         * cause:失败原因
         */
        rabbitTemplate.setConfirmCallback((data,ack,cause) ->{
            assert data != null;
            String msgId = data.getId();
            if(ack){  // 队列收到消息
                LOGGER.info("{}===========>消息发送成功",msgId);
                // 更新消息数据库，更新发送状态为已发送
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",1)
                        .eq("msgId",msgId));
            }else { // 队列未收到消息
                LOGGER.error("{}===========>消息发送失败",msgId);
            }
        });

        /**
         * 消息失败回调，比如路由不到队列时触发回调
         * msg:消息主题
         * repCode:响应码
         * repText:响应描述
         * exchange:交换机
         * routingKey:路由键
         */
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                LOGGER.error("{}===========>消息发送到queue失败",Arrays.toString(returnedMessage.getMessage().getBody()));
            }
        });

        return rabbitTemplate;
    }
    @Bean
    public Queue queue(){ // 消息队列
        return new Queue(MailConstants.MAIL_QUEUE_NAME);
    }

    @Bean
    public DirectExchange exchange(){ // 直连交换机 1-1
        return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME);
    }

    @Bean
    public Binding binding(){ // 用路由器绑定交换机与队列
        return BindingBuilder.bind(queue()).to(exchange()).with(MailConstants.MAIL_ROUTING_KEY_NAME);
    }
}
